import axios from 'axios'

let location = window.location

const service = function (url, data, method = 'GET', headers = {}) {
  return new Promise((resolve, reject) => {
    let options = {
      'method': method,
      'url': process.env.NODE_ENV === 'production' ? process.env.VUE_APP_PC_API + url : `http://${location.host}` + process.env.VUE_APP_PC_API + url,
      'headers': headers && typeof headers === 'object' ? headers : {}
    }
    options.headers['X-Requested-Page'] = 'json'
    // if (Utils.local('accesstoken')) {
    //   options.headers['accesstoken'] = Utils.local('accesstoken')
    // }
    options[method === 'GET' ? 'params' : 'data'] = data
    axios.defaults.withCredentials = true
    axios(options).then((response) => {
      if (response.data.code === 4600) {
        window.location.href = '/login'
      }
      resolve(response.data)
    }).catch((error) => {
      reject(error)
    })
  })
}

export default service
